import { toRefs, onMounted, onUpdated } from "vue"
import { Toast } from "vant"
// 导入store
import { useMapStore } from "../../stores/mapStore"
// 解构map,docLayer
const { mapState } = toRefs(useMapStore())
export const useInitMap = () => {
  const zoomToExtent = new ol.control.ZoomToExtent({
    extent: [114, 30, 114, 32],
  })
  onMounted(() => {
    mapState.value.map = new ol.Map({
      target: "map",
      layers: [imgLayergroup, vecLayergroup],
      view: new ol.View({
        center: [114.379, 30.496],
        zoom: 12,
        projection: "EPSG:4326",
      }),
    })
    setTimeout(() => {
      mapState.value.map.addLayer(mapState.value.docLayer)
      mapState.value.map.addControl(zoomToExtent)
      mapState.value.map.addControl(
        new ol.control.ScaleLine({
          units: "metric",
        })
      )
    }, 200)
  })
  //控制mapbox显隐
  onUpdated(() => {
    if (mapState.value.showCube) {
      Toast.loading({
        message: "加载中...",
        forbidClick: true,
        loadingType: "spinner",
      })
      //mapbox三维图
      mapboxgl.accessToken =
        "pk.eyJ1IjoiemhvbmdkaXNodW1hIiwiYSI6ImNsNXJoYXR5eTI2bGgzZW53d2didWF1c3AifQ.6vOplM2NQc_xnJW3aA5ZBA"
      const map = new mapboxgl.Map({
        container: "cubemap", // container ID
        style: "mapbox://styles/mapbox/streets-v11", // style URL
        center: [-74.5, 40], // starting position [lng, lat]
        zoom: 1, // starting zoom
        projection: "globe", // display the map as a 3D globe
      })
      map.on("style.load", () => {
        map.setFog({}) // Set the default atmosphere style
        // 飞行视角
        setTimeout(() => {
          map.flyTo({
            center: [114.379, 30.496],
            // 值越小,飞行的越慢
            speed: 0.4,
            zoom: 13,
            pitch: 90,
          })
        }, 2000)
      })
      //地图控件
      map.addControl(new mapboxgl.ScaleControl())
      /* 7.搜索 */
      map.addControl(
        new MapboxGeocoder({
          accessToken: mapboxgl.accessToken,
          mapboxgl: mapboxgl,
          placeholder: "请输入地址",
          zoom: 16,
        }),
        "top-left"
      )
    }
  })

  return { mapState }
}
